/**
 * Devin Ellis Sample Code
 * Example Javascript from publicrecords.com
 * This is production code, no changes have been made for this portfolio.
 * 9/23/2011
 */

PR.Events = {
	options: {
		urls: {
			getMessageAttendeesForm: '/api/event/messageform',
			getCreateForm: '/api/event/getcreateform',
			create: '/api/event/create',
			getBandForm: '/api/event/getbandform',
			addBand: '/api/event/addband/',
			getUploadForm: '/api/media/addposter'
		}
	},

	parentID: 0,

	init: function() {
		PR.Events.createEventForm();
		PR.Events.hijackLinks();
		PR.Events.hijackForms();
	},

	hijackLinks: function() {

		// When clicking invite, create a popup
		$('.event-invite').live('click', function(e) {
			e.preventDefault();
			e.stopImmediatePropagation();

			// Open modal with form to invite a friend (connection)
			PR.System.showOverlay();
			$('#overlayInner').html('<h1>Invite</h1>' +
				'<form id="inviteForm" action="/api/messages/send" method="post">' +
				'<input type="text" name="recipients" id="recipients" placeholder="Recipients">' +
				'<input type="submit" name="submit" id="submit" value="Send">'
			);
			PR.Messaging.initAutoComplete();

		});

		// Invite Form Submission
		$('#inviteForm').live('submit', function(e) {
			e.preventDefault();
			e.stopImmediatePropagation();

			PR.Messaging.cleanRecipients();

			dataArray = {
				recipients: PR.Messaging.recipientsID.toString(),
				subject: 'You have been invited to an event',
				threadID: 0,
				allowReply: 'no',
				body: '<a href="/site/profile/view/' + PR.System.you.profileID + '">' + PR.System.you.displayName + '</a>'
			};
			PR.Messaging.validateMessage(dataArray, $(this));
		});

		// When clicking message attendees, show form
		$('.event-message').live('click', function(e) {
			e.preventDefault();
			e.stopImmediatePropagation();
			PR.Events.showMessageAttendees();
		});

		// Create Event, Step 1. Get list of profiles
		$('#createEvent').live('click', function(e) {
			e.preventDefault();
			$.ajax({
				url: PR.Profiles.options.urls.list,
				data: {
					'types': ['admin', 'venue', 'band']
				},

				success: function(data) {
					if (data.status == 'ok') {
						PR.System.showOverlay('newProfile');
						html = '<h1>Create an Event</h1>' + '<p>Create the event as ' + '<select name="parentID" id="parentID">';
						$.each(data.data.profiles, function(i, profile) {
							html += '<option value="' + profile.id + '">' + profile.displayName + '</option>';
						});
						html += '</select></p>' + '<ul id="actionList"><li class="button"><a href="#create" id="eventSaveOwner">Continue</a></li></ul>';
						$('#overlayInner').html(html);
					}
				}
			});
		});

		// Create Event, Step 2
		$('a#eventSaveOwner').live('click', function(e) {
			e.preventDefault();
			parentID = $('#parentID').val();

			// Get event form
			$.ajax({
				url: PR.Events.options.urls.getCreateForm,

				success: function(data) {
					if (data.status == 'ok') {
						$('#overlayInner').html('<h1>Create an Event</h1>' + data.data.eventForm);
						$('.datepicker').datepicker();
					}
				}
			});
		});

		// Create Event, Step 3
		$('#overlay #new_event').live('submit', function(e) {
			e.preventDefault();

			// Submit event form
			$.ajax({
				url: PR.Events.options.urls.create,
				data: $(this).serialize() + '&parentID=' + parentID,

				beforeSend:	function() {
					$(this).css('opacity', '0.5');
				},

				success: function(data) {
					if (data.status == 'ok') {
						// Add Band Form
						var html = '<form id="event_band" class="formClass">' + '<input type="hidden" name="eventID" id="eventID" value="' + data.data.profileID + '">' + '<input type="text" name="bandName" id="bandName" required class="required" placeholder="Band Name">' + '<input type="submit" name="submit" id="submit" value="Add Band">' + '</form>' + '<ul id="bandList"></ul>' + '<ul id="actionList"><li class="button"><a href="#save" id="eventSaveBands">Continue</a></li></ul>';

						$('#overlayInner').html('<h1>Create an Event</h1>' + html);
						PR.Events.hijackForms();
						PR.System.me.profileID = data.data.profileID;
					} else if (data.response == 'Failed') {
						// Event form has errors, display it
						$('#overlayInner').html('<h1>Create an Event</h1>' + data.data + '<ul id="actionList"><li class="button"><a href="#skip" class="closeOverlay">Skip</a></li></ul>');
					}
				}
			});
		});

		// Create Event, Step 4
		$('#eventSaveBands').live('click', function(e) {
			e.preventDefault();
			$('#overlayInner').html('<h1>Create an Event</h1>');
			PR.Events.uploadPoster();
		});

		// Edit Poster
		$('#editPoster').live('click', function(e) {
			e.preventDefault();
			PR.System.showOverlay();
			$('#overlayInner').html('<h1>Replace Poster</h1>');
			PR.Events.uploadPoster();
		});

		/**
		 * Event links in user dashboard have class of changeProfileEvent, we need to pass a second param to switchProfile
		 * with a true value
		 */
		$('.switch-to-event-parent').live('click', function(e) {
			e.preventDefault();
			e.stopImmediatePropagation();
			PR.System.switchEventProfile();
		});
	},

	// get poster upload form
	showMessageAttendees: function() {
		$.ajax({
			url: PR.Events.options.urls.getMessageAttendeesForm,
			type: 'GET',

			success: function(data) {
				PR.System.showOverlay();
				$('#overlayInner').html('<h1>Message Attendees</h1>' + data.data.messageForm);
			}
		});
	},

	// get poster upload form
	uploadPoster: function() {
		$.ajax({
			url: PR.Events.options.urls.getUploadForm,
			type: 'GET',

			success: function(data) {
				if (data.status == 'ok') {
					$('#overlayInner').html($('#overlayInner').html() + data.data.imageForm);
					$('input#image').uploadify({
						'uploader': $('#imageForm').attr('action'),
						'swf': '/assets/swf/uploadify.swf',
						'checkExisting': false,
						'buttonText': 'SELECT IMAGE',
						'fileObjName': 'image',
						'postData': {
							'PHPSESSID': PR.System.me.session
						},
						'cancelImage': '/assets/images/cancel.png',
						'fileTypeDesc': 'Image Files (*.*)',
						'fileTypeExt': '*.jpg;*.jpeg;*.jpe;*.png;*.gif',
						'auto': true,
						'multi': false,
						'fileSizeLimit': 0,
						'width': 100,
						'height': 30,
						'onQueueComplete': function() {
							PR.System.switchProfile(PR.System.me.profileID, true);
						}
					});
				}
			}
		});
	},

	hijackForms: function() {
		$('#new_event').submit(function(e) {
			e.preventDefault();
			e.stopImmediatePropagation();

			dataArray = $(this).serialize();
			PR.Events.updateEvent(dataArray, $(this));
		});

		$('#event_band').submit(function(e) {
			e.preventDefault();
			e.stopImmediatePropagation();

			dataArray = {
				bandName: $(this).find('#bandName').val(),
				eventID: $(this).find('#eventID').val()
			};
			PR.Events.addBand(dataArray);
		});

		$('a.deleteBand').live('click', function(e) {
			e.preventDefault();
			url = $(this).attr('href');

			PR.Events.deleteBand(url, $(this).parent());
		});

		// Message Attendees
		$('#eventMessageAttendees').live('submit', function(e) {
			e.preventDefault();
			$.ajax({
				url: $(this).attr('action'),
				data: $(this).serialize(),

				beforeSend: function() {
				},

				success: function(data) {
					if (data.status == 'ok') {
						$('#overlayInner').html('<h1>Message Attendees</h1><p>Your message was successfully sent.</p>');
					}
				}
			});
		});
	},

	// API call to update an Event
	updateEvent: function(dataArray, $form) {
		$.ajax({
			url: $form.attr('action'),
			data: dataArray,

			beforeSend: function() {
				PR.System.showOverlay();
			},

			success: function(data) {
				if (data.status == "fail") {
					$('#overlayInner').append('<p>There was a problem updating your profile.</p>');
				} else {
					$('#overlayInner').html('<h1>Updated</h1><p>Your event was successfully updated.</p>');
				}
			}
		});
	},

	//Add band to list on event
	addBand: function(dataArray) {
		$.ajax({
			url: PR.Events.options.urls.addBand,
			data: dataArray,

			success: function(data) {
				if (data.status == "fail") {
					PR.System.showOverlay('error');
					$('#overlayInner').append('<p>There was a problem adding the band.</p>');
				} else {
					$('#bandName').val('');
					$('#bandList').append('<li>' + data.data.bandName + ' <a href="/api/event/deleteband/' + data.data.id + '/" class="deleteBand">X</a></li>');

				}
			}
		});
	},

	// Delete a band from an event
	deleteBand: function(url, $item) {
		$.ajax({
			url: url,

			beforeSend: function() {
				PR.System.divLoadingOverlay($('.eventForm'));
			},

			success: function(data) {
				if (data.status == "fail") {
					PR.System.showOverlay('error');
					$('#overlayInner').append('<p>There was a problem deleting the band.</p>');
				} else {
					$('#divLoading').remove();
					$item.remove();
				}
			}
		});
	},

	createEventForm: function() {
		$('#startDate, #endDate').datepicker();
	}
};
